package com.gnerv.sylvanas.framework.core.tools;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * Gson 工具类
 * </p>
 *
 * @author Gnerv LiGen
 */
public class JsonTools {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonTools.class);

    private JsonTools() {
    }

    public static String toJsonString(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return jsonString;
    }

    public static <T> T fromJsonString(String jsonString, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        T t = null;
        try {
            t = objectMapper.readValue(jsonString, clazz);
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return t;
    }

    public static <T> T fromJsonString(String jsonString, TypeReference<T> typeReference) {
        ObjectMapper objectMapper = new ObjectMapper();
        T t = null;
        try {
            t = objectMapper.readValue(jsonString, typeReference);
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return t;
    }

}
